package cn.demo.framework.web.service;

import cn.demo.common.core.domain.entity.SysRole;
import cn.demo.common.core.domain.entity.SysUser;
import cn.demo.common.utils.CollectionUtils;
import cn.demo.common.utils.SecurityUtils;
import cn.demo.sys.service.ISysMenuService;
import cn.demo.sys.service.ISysRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 *
 * @author ruoyi
 */
@Component
public class SysPermissionService {
    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysMenuService menuService;

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRoleKeys(SysUser user) {
        return getRoleKeys(user, roleService.selectRoleSetByUserId(user.getUserId()));
    }
    public Set<String> getRoleKeys(SysUser user, Set<SysRole> roles) {
        Set<String> roleKeys = new HashSet<>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            roleKeys.add("admin");
        } else {
            roleKeys.addAll(roleService.getRolePermission(roles));
        }
        return roleKeys;
    }

    /**
     * 获取菜单数据权限
     *
     * @param user     用户信息
     * @param roleKeys
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(SysUser user, Set<String> roleKeys) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin() || SecurityUtils.isAdmin(roleKeys)) {
            perms.add("*:*:*");
        } else {
            List<SysRole> roles = user.getRoles();
            if (!CollectionUtils.isEmpty(roles)) {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles) {
                    Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            } else {
                perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
            }
        }
        return perms;
    }


}
